<template>
  <div class="patient-reported-right-form">
    <div class="blank">&nbsp;</div>
    <div class="tools">
      <div class="tools-main">
        <i
          style="position: relative; font-size: 18px"
          :class="[
            'el-icon-edit',
            tableStatus &&
            tableStatus.frozen === '1' &&
            tableStatus.isLapse === '1' &&
            tableStatus.isStatus === '2' &&
            permissionController('pi::signature')
              ? 'edit-active'
              : 'colorHover',
          ]"
        >
          <template
            v-if="
              tableStatus &&
              tableStatus.frozen === '1' &&
              tableStatus.isLapse === '1' &&
              tableStatus.isStatus === '2' &&
              permissionController('pi::signature')
            "
          >
            <el-popover v-model="visible" placement="bottom-end" width="400" trigger="click">
              <signature @close="visible = false" @submit="handleSubmitSignature" /><span
                style="
                  display: inline-block;
                  width: 1rem;
                  height: 1rem;
                  position: absolute;
                  left: 0.1rem;
                  top: -0.01rem;
                "
                slot="reference"
              />
            </el-popover>
          </template>
        </i>
        <span
          :class="[
            tableStatus &&
            tableStatus.isLapse === '1' &&
            tableStatus.isStatus === '2' &&
            tableStatus.frozen === '1' &&
            permissionController('crf::form::data::check') &&
            audit.roleCode === findRole
              ? 'edit-active'
              : 'colorHover',
          ]"
          v-for="(audit, index) in audits"
          @click="e => handleApprove(e, audit.tag)"
          :key="index"
          >{{ audit.tag }}</span
        >
        <span class="more">
          <el-dropdown size="medium" trigger="click" @command="handleCommand">
            <span class="el-dropdown-link">&nbsp;</span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="(menu, index) in menus" :command="menu" :key="index">{{
                menu
              }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </span>
      </div>
    </div>
    <div class="form-header">
      <div class="state">
        <span>当前状态：{{ findTableState() }}</span>

        <template>
          <el-button
            size="mini"
            v-if="
              permissionController('crf::form::data::submmit') &&
              tableStatus &&
              tableStatus.isStatus === '1' &&
              tableStatus.isLapse === '1'
            "
            @click="handleSubmit"
            >提交</el-button
          >
          <el-button
            size="mini"
            v-if="
              permissionController('crf::form::data::save') &&
              (!tableStatus ||
                (tableStatus &&
                  tableStatus.frozen === '1' &&
                  tableStatus.isLapse === '1' &&
                  (tableStatus.isStatus === '1' || tableStatus.isStatus === '2')))
            "
            @click="handleSave"
            >保存</el-button
          >
        </template>
        <el-button size="mini" v-if="freeze" @click="handleFreeze">冻结</el-button>
      </div>
      <div class="table-tools">
        <i
          :class="[
            'tool-note',
            handleNotesStatus() === '2' ? 'el-icon-notebook-2' : 'el-icon-edit-outline',
            handleNotesStatus() === '0' ? 'colorDark' : '',
          ]"
          @click="handleNotes"
        ></i>
        <div class="checkbox">
          <el-checkbox
            :disabled="
              !tableStatus ||
              tableStatus.isLapse !== '1' ||
              tableStatus.isStatus === '1' ||
              tableStatus.frozen > 1 ||
              !permissionController('pi::signature')
            "
            v-model="checked['sign']"
            @change="v => handleCheck('sign', v)"
          />
        </div>
        <div v-for="(item, index) in handleTools()" class="checkbox" :key="index">
          <el-checkbox :disabled="item.disabled" v-model="checked[item.tag]" @change="v => handleCheck(item.tag, v)" />
        </div>
        <div :class="`question question-${handleQuestionStatus()}`" @click="handleQuestion">&nbsp;</div>
      </div>
    </div>
    <div class="form-main">
      <CustomForm
        ref="customForm"
        :table-field-list="subjectData.mainTable.tableFieldList"
        :table-status="subjectData.tableStatus"
        :table-field-rules="rules"
        :channel="channel"
        :checkboxed="checkboxed"
        :originSubjectData="isAdd ? subjectData.embeddedTable : original && original.embeddedTable"
        :table-field-config="subjectData.tableFieldConfig"
        :from-data-normal="subjectData.fromDataNormal"
        :embedded-table="subjectData.embeddedTable"
        :embedded-table-rendering="subjectData.embeddedTableRendering"
        :isAddEm="isAddEm"
        :isAddList="isAddList"
        :isAdd="isAdd"
        :addSortNum="addSortNum"
        @delete="(embeddedTableKey, index) => handleDelete(embeddedTableKey, index)"
        @add-inner="embeddedTableKey => handleAddInner(embeddedTableKey)"
        @handleEmbedded="handleEmbedded"
      ></CustomForm>
    </div>
    <el-dialog
      title="研究者批注"
      :visible.sync="dialogNotesVisible"
      :width="dataNotes && dataNotes.length > 0 ? '800px' : '500px'"
      :destroy-on-close="true"
      :append-to-body="true"
    >
      <notes
        size="mini"
        type="1"
        :table-status="subjectData.tableStatus"
        :table-data="dataNotes"
        @close="handleCloseNotes"
      />
    </el-dialog>
    <el-dialog title="修改原因" :modal="false" :visible.sync="dialogReasonVisible" width="700px">
      <reason :table-data="reasons" @close="dialogReasonVisible = false" @callback="handleModify" />
    </el-dialog>
    <el-dialog
      title="撤销"
      :visible.sync="dialogRevokeSubmitVisible"
      width="30%"
      :append-to-body="true"
      :destroy-on-close="true"
    >
      <div style="margin-top: 0.5rem">
        <span style="float: left; margin-right: 10px; margin-top: 4px">撤销原因:</span
        ><el-input style="width: 80%" size="mini" v-model="revokeSubmitReason" />
      </div>
      <div style="text-align: right; margin-top: 0.6rem">
        <el-button type="primary" size="mini" :disabled="!revokeSubmitReason" @click="revokeSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 增加质疑 -->
    <el-dialog
      title="增加质疑"
      :visible.sync="dialogAddQuestionVisible"
      width="550px"
      :destroy-on-close="true"
      :append-to-body="true"
    >
      <add-question
        :queryType="queryType"
        :table-status="subjectData.tableStatus"
        @callback="
          () => {
            dialogAddQuestionVisible = false
            upgrade()
          }
        "
      />
    </el-dialog>
    <!-- 质疑列表 -->
    <el-dialog
      title="质疑列表"
      width="800px"
      :visible.sync="dialogQuestionVisible"
      :destroy-on-close="true"
      :append-to-body="true"
      :close-on-click-modal="false"
      :before-close="closeDialogQuestion"
    >
      <question
        :queryType="queryType"
        v-if="dialogQuestionVisible"
        :table-status="subjectData.tableStatus"
        @create="createQuestion"
        :dialogQuestionVisible="dialogQuestionVisible"
        :queryListData="queryListData"
        style="height: 600px; overflow: auto"
      />
    </el-dialog>
    <el-dialog
      title="提示"
      :visible.sync="dialogInvalidVisible"
      width="30%"
      :append-to-body="true"
      :destroy-on-close="true"
    >
      <invalid
        size="mini"
        :type="command"
        :implicated.sync="implicated"
        :invalidParams="invalidParams"
        :table-status="subjectData.tableStatus"
        :table-field-list="subjectData.mainTable.tableFieldList"
        :show-events="showEvents"
        @close="dialogInvalidVisible = false"
      />
    </el-dialog>
    <el-dialog title="稽查轨迹" :visible.sync="dialogAuditTrailVisible" width="80%" :append-to-body="true">
      <audit-trail
        v-if="dialogAuditTrailVisible"
        :table-status="subjectData.tableStatus"
        :dialogVisible="dialogAuditTrailVisible"
        :table-field-list="subjectData.mainTable.tableFieldList"
        :operateTypes="operateTypes"
        :variableNames="variableNames"
        :embedded-table-rendering="subjectData.embeddedTableRendering"
        @close="dialogAuditTrailVisible = false"
      />
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
import CustomForm from './custom-form/index.vue'
import signature from './signature.vue'
import addQuestion from './add-question.vue'
import reason from './reason.vue'
import notes from './notes.vue'
import Question from './question.vue'
import invalid from './invalid.vue'
import auditTrail from './auditTrail.vue'
import { permissionController } from '@/utils/index'

export default {
  data() {
    return {
      checked: {},
      subjectData: {
        mainTable: {
          tableStatus: null,
          tableFieldList: null,
        },
        embeddedTable: {},
        tableFieldConfig: {},
        fromDataNormal: null,
        embeddedTableRendering: null,
      },
      originalSubjectData: {
        mainTable: {
          tableStatus: null,
          tableFieldList: null,
        },
        embeddedTable: [],
        fromDataNormal: null,
        embeddedTableRendering: null,
      },
      dialogNotesVisible: false,
      dataNotes: [],
      dialogQuestionVisible: false,
      dialogAddQuestionVisible: false,
      save: false,
      submit: false,
      dialogAuditTrailVisible: false,
      visible: false,
      dialogReasonVisible: false,
      reasons: [],
      added: [],
      dialogRevokeSubmitVisible: false,
      revokeSubmitReason: '',
      command: null,
      dialogInvalidVisible: false,
      implicated: null,
      showEvents: null,
      freeze: false,
      rules: {},
      menus: [],
      tools: [],
      isAdd: false,
      queryType: '0',
      queryListData: [],
      checkboxed: false,
      invalidParams: {},
      variableNames: [],
      operateTypes: [],
    }
  },
  props: {
    source: {
      type: [Object, Array],
    },
    original: {
      type: [Object, Array],
    },
    channel: {
      type: String,
    },
    isAddEm: {
      type: Boolean,
    },
    addSortNum: {
      type: Number,
    },
    isAddList: {
      type: Boolean,
    },
  },
  components: {
    signature,
    addQuestion,
    CustomForm,
    reason,
    notes,
    Question,
    invalid,
    auditTrail,
  },
  computed: {
    ...mapState({
      subjectInfo: state => state.treatment.subjectInfo,
      audits: state => state.treatment.audits,
      visit: state => state.treatment.visit,
      table: state => state.treatment.table,
      stateOptions: state => state.treatment.stateOptions,
      frozenOptions: state => state.treatment.frozenOptions,
      relations: state => state.treatment.relations,
    }),
    ...mapGetters({
      findRole: 'treatment/findRole',
      isWriteRole: 'treatment/isWriteRole',
    }),
    newObj() {
      return JSON.parse(JSON.stringify(this.original))
    },

    tableStatus() {
      if (this.subjectData && this.subjectData.tableStatus) {
        return this.subjectData.tableStatus
      } else {
        return null
      }
    },
  },

  mounted() {
    setTimeout(() => {
      if (this.source) {
        if (this.source instanceof Array) {
          this.subjectData = this.source[0]
          this.originalSubjectData = this.original[0]
        } else {
          this.originalSubjectData = this.original
          this.subjectData = this.source
        }
        if (this.tableStatus) {
          this.handleChecked()
        }
        this.handleDefaultValues()
        this.handleEmbeddedTableCompatible()
        this.initFormRules()
        this.findMenus()
        this.handleTools()
      }
    })
  },
  watch: {
    newObj: {
      handler: function (val) {
        if (val instanceof Array) {
          this.originalSubjectData = val[0]
        } else {
          this.originalSubjectData = val
        }
      },
      deep: true,
      immediate: true,
    },
    source: {
      handler: function (val) {
        if (val instanceof Array) {
          this.subjectData = val[0]
          this.originalSubjectData = this.original[0]
        } else {
          this.originalSubjectData = this.original
          this.subjectData = val
        }
      },
      deep: true,
      immediate: true,
    },
  },

  methods: {
    permissionController,
    ...mapActions('eCRFDetail', [
      'saveSubjectData',
      'getEmbeddedTable',
      'annotationList',
      'getQueryListAPI',
      'addQueryAutoCheckRule',
      'updateSign',
      'updateTableStatus',
      'getTypeAndName',
    ]),
    ...mapMutations({
      upgrade: 'treatment/upgrade',
    }),
    createQuestion() {
      this.dialogQuestionVisible = false
      this.dialogAddQuestionVisible = true
    },
    // 初始化表单校验规则
    initFormRules() {
      const tableFieldList = this.subjectData.mainTable.tableFieldList
      tableFieldList.forEach(data => {
        if (data.required == '0') {
          const _self = this
          this.rules[data.variable] = [
            {
              required: data.required == '0',
              validator: (rule, value, callback) => {
                callback(_self.validatorEx(rule, value, data))
              },
            },
          ]
        }
      })
    },
    validatorEx: function (rule, value, data) {
      if (data.controlled) {
        return ''
      }
      if (data.required == '0') {
        if (['', null, undefined].includes(value)) {
          return new Error('数据不能为空！')
        } else {
          return
        }
      }
      if (data.regEx) {
        const regExp = new RegExp(data.regEx)
        if (regExp.test(value)) {
          return ''
        } else {
          return new Error('错误，正则验证未通过！')
        }
      } else {
        return ''
      }
    },
    handleCommand(command) {
      this.command = command
      switch (command) {
        case '失效':
          this.dialogInvalidVisible = true
          if (this.subjectData.tableStatus) {
            this.invalidParams = this.handleBaseParams(false)
          } else {
            this.invalidParams = this.handleBaseParams(true)
          }
          break
        case '激活':
          this.dialogInvalidVisible = true
          break
        case '撤销':
          this.dialogRevokeSubmitVisible = true
          break
        case '解冻':
          this.unfreeze()
          break
        case '稽查轨迹':
          this.dialogAuditTrailVisible = true
          this.getOpearteType()
          break
      }
    },

    getOpearteType() {
      const { subjectId, visitId } = this.table
      const params = {
        subjectId,
        visitId,
        subjectDataId: this.tableStatus && this.tableStatus.formDataId,
      }
      this.getTypeAndName({ params }).then(res => {
        const { code, data } = res
        if (code === 200) {
          this.operateTypes = data.operateTypes || []
          this.variableNames = data.variableNames || []
        }
      })
    },
    // 批准按钮权限状态
    handleNotesStatus() {
      if (!this.permissionController('crf::form::data::annotation')) {
        return '0'
      }
      if (this.tableStatus) {
        if (this.tableStatus.isLapse === '1' && this.tableStatus.frozen === '1') {
          return this.tableStatus.isNote
        } else {
          return '0'
        }
      } else {
        return '0'
      }
    },

    handleEmbedded(val) {
      if (this.originalSubjectData) {
        this.originalSubjectData.embeddedTable = JSON.parse(JSON.stringify(val))
      }
    },

    handleChecked() {
      const {
        tableStatus: { statisticsCra, statisticsDm, statisticsPm, statisticsMm, statisticsPi },
      } = this.subjectData
      this.handleAudits('cra', statisticsCra === '3')
      this.handleAudits('dm', statisticsDm === '3')
      this.handleAudits('pm', statisticsPm === '3')
      this.handleAudits('mm', statisticsMm === '3')
      this.handleAudits('pi', statisticsPi === '3')
    },

    handleAudits(keywords, checked) {
      if (keywords === 'pi') {
        this.$set(this.checked, 'sign', checked)
      } else {
        const { code } = this.relations.filter(relation => relation.alias == keywords)[0]
        const target = this.audits.filter(audit => audit.roleCode == code)[0]
        target && this.$set(this.checked, target.tag, checked)
      }
    },

    handleDefaultValues() {
      const tableFieldConfig = this.subjectData.tableFieldConfig
      if (tableFieldConfig && Reflect.has(tableFieldConfig, 'defaultValues')) {
        const { defaultValues } = tableFieldConfig
        if (defaultValues && defaultValues.length > 0) {
          defaultValues.forEach(defaultValue => {
            const target = this.subjectData.mainTable.tableFieldList.filter(
              tableField => tableField.variable == defaultValue.tableField
            )[0]
            target && (target.variableValue = defaultValue.fieldValue)
          })
        }
      }
    },

    handleEmbeddedTableCompatible() {
      this.subjectData.mainTable &&
        this.subjectData.mainTable.tableFieldList &&
        this.subjectData.mainTable.tableFieldList.forEach(tableField => {
          const { type, embeddedTableKey } = tableField
          if (type === '3') {
            if (this.subjectData.embeddedTable) {
              if (!Reflect.has(this.subjectData.embeddedTable, embeddedTableKey)) {
                this.$set(this.subjectData.embeddedTable, embeddedTableKey, [])
              }
            } else {
              this.$set(this.subjectData, 'embeddedTable', {})
              this.$set(this.subjectData.embeddedTable, embeddedTableKey, [])
            }
          }
        })
    },
    // 判断右侧按钮显隐
    findMenus() {
      let menus = []
      if (this.tableStatus) {
        const { isStatus, isLapse } = this.tableStatus
        if (isStatus === '1') {
          // 默认有数据录入的权限才能有失效/激活
          if (this.permissionController('subject::ecrf::data::entery')) {
            if (isLapse === '1' && this.permissionController('crf::form::data::invalid')) {
              this.save = true
              this.submit = true
              menus.push('失效')
            } else if (
              (isLapse === '2' || isLapse === '3') &&
              this.permissionController('crf::form::data::track::activate')
            ) {
              this.save = false
              this.submit = false
              menus.push('激活')
            }
          } else {
            this.save = false
            this.submit = false
          }
        } else if (isStatus === '2') {
          this.submit = false
          if (this.permissionController('subject::ecrf::data::entery')) {
            if (isLapse === '1') {
              this.save = true
              if (
                this.permissionController('crf::form::data::invalid') &&
                this.permissionController('crf::form::data::thaw')
              ) {
                menus.push('撤销', '失效')
              }
              if (
                this.permissionController('crf::form::data::invalid') &&
                !this.permissionController('crf::form::data::thaw')
              ) {
                menus.push('失效')
              }
              if (
                !this.permissionController('crf::form::data::invalid') &&
                this.permissionController('crf::form::data::thaw')
              ) {
                menus.push('撤销')
              }
            } else if (
              (isLapse === '2' || isLapse === '3') &&
              this.permissionController('crf::form::data::track::activate')
            ) {
              this.save = false
              menus.push('激活')
            }
          } else if (this.permissionController('crf::form::data::unfreeze')) {
            this.freeze = this.isFreezeShow()
          }
        }
        menus.push('稽查轨迹')
        if (this.tableStatus.frozen !== '1') {
          menus = ['稽查轨迹']
          if (this.permissionController('crf::form::data::unfreeze')) {
            menus.unshift('解冻')
          }
        }
      } else {
        if (
          this.permissionController('subject::ecrf::data::entery') &&
          this.permissionController('crf::form::data::invalid') &&
          ![5, 6].includes(this.table.extandStatus.tableStatus)
        ) {
          this.save = true
          this.submit = true
          menus.push('失效')
        }
      }
      this.menus = menus
    },
    // 工具栏展示
    handleTools(columns) {
      const result = []
      this.audits.forEach(audit => {
        const obj = {
          ...audit,
        }
        obj.disabled =
          audit.roleCode !== this.findRole ||
          !this.tableStatus ||
          this.tableStatus.isLapse === '2' ||
          this.tableStatus.isLapse === '3' ||
          this.tableStatus.isStatus === '1' ||
          this.tableStatus.frozen !== '1' ||
          !this.permissionController('crf::form::data::check')
        if (columns) {
          obj.enable = this.converterMerge(audit, columns)
        }
        result.push(obj)
      })
      return result
    },
    converterMerge(audit, columns) {
      let enable = columns
        .map(col => {
          const { fromDataChecksetupDTO } = col
          if (fromDataChecksetupDTO && Object.keys(fromDataChecksetupDTO).length > 0) {
            return parseInt(this.converter(audit, fromDataChecksetupDTO))
          } else {
            return 0
          }
        })
        .reduce((p, c) => p + c)

      if (enable > 0) {
        return 1
      } else {
        return 0
      }
    },
    converter(audit, fromDataChecksetupDTO) {
      if (!fromDataChecksetupDTO) {
        return '0'
      }
      let result
      const { checkSetupOne, checkSetupTwo, checkSetupThree, checkSetupFour, checkSetupFive } = fromDataChecksetupDTO
      switch (audit.sort) {
        case 1:
          result = checkSetupOne
          break
        case 2:
          result = checkSetupTwo
          break
        case 3:
          result = checkSetupThree
          break
        case 4:
          result = checkSetupFour
          break
        case 5:
          result = checkSetupFive
          break
      }
      return result
    },
    // 关闭批注弹框
    handleCloseNotes() {
      this.dataNotes = []
      this.table.extandStatus.commentState = 2
      this.dialogNotesVisible = false
    },
    // 质疑按钮点击
    async handleQuestion(e) {
      const classList = e.currentTarget.classList
      for (let v of classList.values()) {
        if (v && v.startsWith('question-')) {
          const arr = v.split('-')
          if (arr[1] === '0' || arr[1] === '1') {
            return
          } else if (arr[1] === '5') {
            this.dialogAddQuestionVisible = true
            return
          }
        }
      }
      // 接口放到外面
      let params = { id: this.subjectData.tableStatus.formDataId }
      const res = await this.getQueryListAPI({ params })
      if (res.code === 200) {
        this.queryListData = res.data
        this.dialogQuestionVisible = true
      }
    },
    // 判断是否冻结
    isFreezeShow() {
      if (this.tableStatus.frozen === '2') {
        return false
      }

      if (this.audits && this.audits.length > 0) {
        let flag = false
        this.audits.forEach(audit => {
          const { roleCode } = audit
          let prefix = roleCode
          if (prefix === 'Medical') {
            prefix = 'mm'
          }
          if (prefix === 'Site_PI') {
            prefix = 'pi'
          }
          const target = ['statisticsCra', 'statisticsDm', 'statisticsMm', 'statisticsPi', 'statisticsPm'].filter(
            key => key.toLowerCase() === `statistics${prefix.toLowerCase()}`
          )[0]
          if (this.tableStatus[target] === '3') {
            flag = true
            return
          }
        })
        return flag
      }
      return this.permissionController('crf::form::data::freeze')
    },
    //获取质疑按钮状态
    handleQuestionStatus() {
      if (this.tableStatus) {
        if (this.tableStatus.isStatus === '1') {
          return 1
        }
        if (Reflect.has(this.tableStatus, 'isQuestion')) {
          const question = this.tableStatus.isQuestion
          if (question === '1') {
            if (this.permissionController('send::challenge')) {
              if (this.tableStatus.isLapse === '1' && this.tableStatus.frozen === '1') {
                return 5
              } else {
                return 1
              }
            }
          } else if (question === '2') {
            if (this.permissionController('send::challenge')) {
              return `${question}-2`
            } else {
              return `${question}-1`
            }
          }
          return question
        } else {
          if (this.tableStatus.islapse === '1' && this.tableStatus.frozen === '1') {
            return 5
          } else {
            return 1
          }
        }
      } else {
        return 1
      }
    },
    // 判断表格按钮状态
    findTableState() {
      if (this.tableStatus) {
        const { isStatus, frozen, isLapse } = this.tableStatus
        if (frozen === '1') {
          if (isLapse === '1') {
            return this.stateOptions[isStatus]
          } else {
            return '失效'
          }
        } else {
          return this.frozenOptions[frozen]
        }
      } else {
        return ''
      }
    },
    // 提交电子签名
    handleSubmitSignature(params) {
      this.handleApprove(null, 'sign', params)
      this.visible = false
    },
    // 撤销
    revokeSubmit() {
      const params = {
        id: this.tableStatus.formDataId,
        statusType: '2',
        status: '1',
        roleId: localStorage.getItem('roleId')
      }
      this.updateTableStatus({ params })
        .then(res => {
          const { code } = res
          if (code === 200) {
            this.dialogRevokeSubmitVisible = false
            this.$message.success('操作成功！')
            this.revokeSubmitReason = ''
            this.upgrade()
          }
        })
        .catch(error => {
          this.$message.error(error)
        })
    },
    closeDialogQuestion() {
      this.dialogQuestionVisible = false
      this.upgrade()
    },
    // 批注
    handleNotes() {
      if (
        this.permissionController('crf::form::data::annotation') &&
        this.tableStatus &&
        this.tableStatus.isLapse === '1' &&
        this.tableStatus.frozen === '1'
      ) {
        this.findNotes()
      }
    },
    // 获取批注信息
    findNotes() {
      const params = {
        detailsId: this.tableStatus.formDataId,
        annotationType: '1',
      }
      this.annotationList({ params }).then(res => {
        const { code, data } = res
        if (code === 200) {
          this.dataNotes = data
          this.dialogNotesVisible = true
        }
      })
    },
    // 保存
    handleSave() {
      this.$refs['customForm'].validate().then(valid => {
        if (valid) {
          if (this.tableStatus) {
            if (this.tableStatus.activeType === '1') {
              this.handleDifference()
            }
            if (this.tableStatus.activeType === '0' || this.reasons.length == 0) {
              if (this.tableStatus.activeType === '0' || this.added.length > 0) {
                const data = {
                  ...this.handleBaseParams(false),
                }
                this.saveSubjectData({ data }).then(res => {
                  const { code, message } = res
                  if (code === 200) {
                    this.$emit('upload')
                    this.upgrade()
                    this.$message.success('保存成功！')
                  }
                })
              } else {
                this.$message.warning('数据没有修改，无须保存')
              }
            } else {
              this.reasons.push({})
              this.dialogReasonVisible = true
            }
          } else {
            const data = {
              ...this.handleBaseParams(true),
            }
            this.saveSubjectData({ data }).then(res => {
              const { code } = res
              if (code === 200) {
                this.$emit('upload')
                this.upgrade()
                this.$message.success('保存成功！')
              }
            })
          }
        }
      })
    },
    // 提交
    handleSubmit() {
      this.$refs['customForm'].validate().then(valid => {
        if (valid) {
          this.handleDifference()
          if (this.added.length > 0 || this.reasons.length > 0) {
            this.$message.warning('有数据变动，请先保存！')
          } else {
            this.updateSubjectDataState({
              subjectData: this.handleBaseParams(false, '2'),
              type: '1',
            })
          }
        }
      })
    },
    // 提交api
    updateSubjectDataState(params) {
      const data = {
        ...params.subjectData,
      }
      this.saveSubjectData({ data }).then(res => {
        const { code } = res
        if (code === 200) {
          this.$emit('upload')
          this.upgrade()
          this.$message.success('操作成功！')
        }
      })
    },

    // 数据比对
    handleDifference() {
      this.reasons.length = 0
      this.added.length = 0
      const { id } = this.subjectInfo
      const {
        mainTable: { tableFieldList },
        embeddedTable,
      } = this.subjectData
      const {
        mainTable: { tableFieldList: originalTableFieldList },
        embeddedTable: originalEmbeddedTable,
      } = this.originalSubjectData
      tableFieldList &&
        tableFieldList.forEach(tableField => {
          const {
            type,
            variable,
            variableType,
            variableName,
            variableValue,
            formFieldId,
            formDataId,
            embeddedTableKey,
            databaseCodeValueDTO,
          } = tableField
          if (type === '1') {
            const target = originalTableFieldList.filter(
              originalTableField => originalTableField.variable === variable
            )[0]

            // 判断值是否相等
            if (target.variableValue !== null && variableValue !== '') {
              if (target.variableValue === '' && (variableValue === '' || variableValue === undefined)) {
                return
              }
              if (target.variableValue !== variableValue) {
                let fieldNewValue
                let fieldOldValue
                if (variableValue) {
                  fieldNewValue = this.handleCodeDescribe(variableType, variableValue, databaseCodeValueDTO)
                }
                if (target.variableValue) {
                  fieldOldValue = this.handleCodeDescribe(variableType, target.variableValue, databaseCodeValueDTO)
                }
                // 修改原因参数
                this.reasons.push({
                  projectId: localStorage.getItem('sys-project-id'),
                  visitId: this.visit.selectId,
                  subjectId: id,
                  formName: this.table.tableName,
                  crfName: this.table.config.tableCode,
                  formKey: this.table.selectId,
                  variableName,
                  variableId: formFieldId,
                  variableKey: variable,
                  variableValueOperate: variableValue,
                  fieldNewValue,
                  variableOldValue: target.variableValue,
                  fieldOldValue,
                  reason: '',
                  sortNum: target.sort,
                  handleName: localStorage.getItem('userName'),
                  handleRole: this.findRole.roleName,
                  handleType: '数据修改',
                  subjectDataId: formDataId,
                })
              }
            }
          } else if (type === '3') {
            // 当前数据
            const array = embeddedTable[embeddedTableKey]
            // 原始数据
            let originalArray = originalEmbeddedTable
            if (!originalArray) {
              originalArray = []
            }

            if (array && array.length > 0) {
              array.forEach((object, index) => {
                const { tableFieldList } = object
                if (originalArray[index]) {
                  tableFieldList.forEach(tableField => {
                    const {
                      variable,
                      variableType,
                      variableName: originalVariableName,
                      variableValue,
                      formFieldId,
                      formDataId,
                      databaseCodeValueDTO,
                    } = tableField

                    const { tableFieldList } = originalArray[index]
                    const target = tableFieldList.filter(
                      originalTableField => originalTableField.variable == variable
                    )[0]

                    if (target.variableValue || variableValue) {
                      if (target.variableValue != variableValue) {
                        let fieldNewValue
                        let fieldOldValue
                        if (variableValue) {
                          fieldNewValue = this.handleCodeDescribe(variableType, variableValue, databaseCodeValueDTO)
                        }
                        if (target.variableValue) {
                          fieldOldValue = this.handleCodeDescribe(
                            variableType,
                            target.variableValue,
                            databaseCodeValueDTO
                          )
                        }
                        this.reasons.push({
                          projectId: localStorage.getItem('sys-project-id'),
                          visitId: this.visit.selectId,
                          subjectId: id,
                          crfName: embeddedTableKey,
                          variableName: `${variableName}-${index + 1}.${originalVariableName}`,
                          variableId: formFieldId,
                          variableKey: variable,
                          variableValueOperate: variableValue,
                          fieldNewValue,
                          variableOldValue: target.variableValue,
                          fieldOldValue,
                          reason: '',
                          sortNum: target.sort,
                          handleName: sessionStorage.getItem('userName'),
                          handleRole: this.findRole.roleName,
                          handleType: '数据修改',
                          subjectDataId: formDataId,
                        })
                      }
                    }
                  })
                } else {
                  tableFieldList.forEach(tableField => {
                    const { variable, variableName: originalVariableName, variableValue, formFieldId } = tableField
                    this.added.push({
                      projectId: localStorage.getItem('sys-project-id'),
                      visitId: this.visit.selectId,
                      subjectId: id,
                      crfName: embeddedTableKey,
                      variableName: `${variableName}-${index + 1}.${originalVariableName}`,
                      variableId: formFieldId,
                      variableKey: variable,
                      variableValueOperate: variableValue,
                      reason: '',
                      handleName: localStorage.getItem('userName'),
                      handleRole: this.findRole.roleName,
                      handleType: '数据录入',
                    })
                  })
                }
              })
            }
          }
        })
    },

    // 初始化表单数据
    handleCodeDescribe(variableType, value, databaseCodeValueDTO) {
      if (variableType === '10') {
        const list = databaseCodeValueDTO.filter(item => item.codeValue == value)
        if (list && list.length > 0) {
          const { codeDescribe } = list[0]
          return codeDescribe
        }
      } else if (variableType === '20') {
        const arr = value.split(',')
        return arr
          .map(v => {
            const list = databaseCodeValueDTO.filter(item => item.codeValue == v)
            if (list && list.length > 0) {
              const { codeDescribe } = list[0]
              return codeDescribe
            }
          })
          .join(',')
      } else {
        return value
      }
    },

    // 提交/保存组合参数
    handleBaseParams(isFirst, status) {
      const { coreId, id, databaseId, databaseVersion } = this.subjectInfo
      // 公共参数
      const publicRequest = {
        projectId: localStorage.getItem('sys-project-id'),
        databaseId,
        databaseVersion,
        environment: localStorage.getItem('environment'),
        subjectId: id,
        crfName: this.table.config.tableCode,
        crfCNName: this.table.tableName,
        coreId,
        visitId: this.visit.visitId,
        visitName: this.visit.visitName,
        visitSelectId: this.table.selectId,
        subjectVisit: this.visit.id,
        subjectTable: this.table.id,
        isStatus: (this.tableStatus && this.tableStatus.isStatus) || null,
        roleId: localStorage.getItem('roleId'),
      }
      // 非首次触发
      if (!isFirst) {
        publicRequest.formDataId = this.tableStatus.formDataId
      }
      const mainTable = []
      const embeddedTable = []
      this.subjectData.mainTable.tableFieldList.forEach(tableField => {
        const {
          type,
          variable,
          variableName,
          variableValue,
          voluntarilyIds,
          checkRuleId,
          embeddedTableKey,
          formFieldId,
          formDataId,
          fieldVariableValue,
        } = tableField
        if (type === '1') {
          const object = {
            crfName: this.table.config.tableCode,
            variable,
            variableName,
            variableValue: variableValue || '',
            voluntarilyIds,
            checkRuleId,
            formFieldId,
            fieldVariableValue
          }
          if (!isFirst) {
            object.formFieldId = formFieldId ? formFieldId : ''
            object.formDataId = formDataId ? formDataId : this.tableStatus.formDataId
          }
          mainTable.push(object)
        } else if (type === '3') {
          const array = this.subjectData.embeddedTable[embeddedTableKey]
          array &&
            array.length > 0 &&
            array.forEach(object => {
              const { tableFieldList } = object
              const arr = tableFieldList.map(tableField => {
                const {
                  checkRuleId,
                  variable,
                  variableName,
                  variableValue,
                  formFieldId,
                  formDataId,
                  fieldVariableValue,
                } = tableField
                const object = {
                  checkRuleId,
                  crfName: embeddedTableKey,
                  variable,
                  variableName,
                  variableValue: variableValue || '',
                  formFieldId,
                  fieldVariableValue
                }

                if (!isFirst) {
                  object.formFieldId = formFieldId ? formFieldId : ''
                  object.formDataId = formDataId ? formDataId : null
                }
                return object
              })
              // 排序专用
              if (arr[0].variableName === '序号' && arr[0].variableValue) {
                arr.forEach(item => {
                  item.sortNum = arr[0].variableValue
                })
              }

              embeddedTable.push(arr)
            })
        }
      })
      return {
        publicRequest,
        mainTable,
        operateType: status === '2' ? '2' : '1',
        embeddedTable,
      }
    },
    handleEmbeddedIsApprove(embeddedTableKey, keywords) {
      const columns = this.subjectData.embeddedTableRendering[embeddedTableKey]
      const tools = this.handleTools(columns)
      const { code } = this.relations.filter(relation => relation.alias == keywords)[0]
      const target = tools.filter(tool => tool.roleCode == code)[0]
      if (target && (target.disabled || target.enable == 0)) {
        return -1
      } else {
        return 1
      }
    },

    handleMainIsApprove(tableField, keywords) {
      const customForm = this.$refs.customForm
      const tools = customForm.handleTools(tableField.fromDataChecksetupDTO)
      const { code } = this.relations.filter(relation => relation.alias == keywords)[0]
      const target = tools.filter(tool => tool.roleCode == code)[0]
      if (target && (target.disabled || target.enable == 0)) {
        return -1
      } else {
        return 1
      }
    },

    handleAddInner(embeddedTableKey) {
      this.isAdd = true
      let embeddedTable
      let tableFieldList = this.subjectData.embeddedTableRendering[embeddedTableKey]

      let embeddedTableNew = JSON.parse(JSON.stringify(this.subjectData.embeddedTable))
      const clone = JSON.parse(JSON.stringify({ tableFieldList, new: true }))
      clone.tableFieldList.forEach(item => {
        if (item.variableName !== '序号') {
          item.variableValue = item.defaultValue
        } else {
          if (
            embeddedTableNew &&
            Reflect.has(embeddedTableNew, embeddedTableKey) &&
            embeddedTableNew[embeddedTableKey].length > 0
          ) {
            embeddedTable = JSON.parse(JSON.stringify(embeddedTableNew[embeddedTableKey]))
            const last = embeddedTable[embeddedTable.length - 1]
            const e = last.tableFieldList.filter(item => item.variableName === '序号')[0]
            item.variableValue = last.tableFieldList.length + 1
            item.formFieldId = ''
          } else {
            if (!embeddedTableNew) {
              this.$set(this.subjectData, 'embeddedTable', {})
            }
            this.$set(this.subjectData.embeddedTable, embeddedTableKey, embeddedTableNew[embeddedTableKey])
            embeddedTable = embeddedTableNew[embeddedTableKey]
            item.variableValue = 1
          }
        }
      })
      embeddedTable.push(clone)
      this.$nextTick(() => {
        this.$set(this.subjectData.embeddedTable, embeddedTableKey, embeddedTable)
        this.$forceUpdate()
      })
    },

    handleDelete(embeddedTableKey, index) {
      const embeddedTable = this.subjectData.embeddedTable[embeddedTableKey]
      embeddedTable.splice(index, 1)
    },
    handleCheck(tag, checked) {
      const customForm = this.$refs.customForm
      const {
        mainTable: { tableFieldList },
        embeddedTable,
        embeddedTableRendering,
      } = this.subjectData
      tableFieldList.forEach(tableField => {
        const { type, variable, embeddedTableKey } = tableField
        // 正常表单
        if (type === '1') {
          const tools = customForm.handleTools(tableField.fromDataChecksetupDTO)
          const target = tools.filter(tool => tool.tag === tag && tool.roleCode === this.findRole)[0]
          if (target) {
            if (target.disabled || target.enable == 0) {
              this.$set(customForm.form, `$${variable}--${tag}`, false)
            } else {
              this.$set(customForm.form, `$${variable}--${tag}`, checked)
            }
          } else {
            this.$set(customForm.form, `$${variable}--${tag}`, checked)
          }
        } else if (type === '3') {
          this.checkboxed = true
          const f = customForm.form[embeddedTableKey]
          const arr = embeddedTable[embeddedTableKey]
          const columns = embeddedTableRendering[embeddedTableKey]
          const tools = this.handleTools(columns)
          const target = tools.filter(tool => tool.tag === tag)[0]
          for (let i = 0; i < arr.length; i++) {
            if (target) {
              if (target.disabled || target.enable == 0) {
                this.$set(f, `$${embeddedTableKey}--${i}--${tag}`, false)
              } else {
                this.$set(f, `$${embeddedTableKey}--${i}--${tag}`, checked)
              }
            } else {
              this.$set(f, `$${embeddedTableKey}--${i}--${tag}`, checked)
            }
          }
        }
      })
    },
    // 修改
    handleModify() {
      const subjectDataSavaRequest = {
        ...this.handleBaseParams(),
      }
      let dataList = []
      if (this.added.length > 0) {
        dataList = dataList.concat(this.added.slice(0, this.added.length - 1))
      }
      if (this.reasons.length > 0) {
        dataList = dataList.concat(this.reasons.slice(0, this.reasons.length - 1))
      }
      const data = {
        dataList,
        ...subjectDataSavaRequest,
        operateType: '1',
      }
      this.saveSubjectData({ data }).then(res => {
        const { code, message } = res
        if (code == 200) {
          this.$emit('upload')
          this.upgrade()
          this.dialogReasonVisible = false
          this.$message.success('操作成功！')
        }
      })
    },
    handleApprove(event, tag, params = {}) {
      let has = true
      if (event) {
        const classList = event.currentTarget.classList
        has = classList.contains('edit-active')
      }
      if (has) {
        const customForm = this.$refs.customForm
        const { id } = this.subjectInfo
        const { formDataId } = this.tableStatus
        const { type, alias } = this.relations.filter(item => {
          return item.code === this.findRole
        })[0]
        const {
          mainTable: { tableFieldList },
          embeddedTable,
          embeddedTableRendering,
        } = this.subjectData
        const mTable = []
        const eTable = []
        tableFieldList.forEach(tableField => {
          const { variable, formFieldId, crc, cra, dm, pm, mm, pi, embeddedTableKey } = tableField
          if (tableField.type === '1') {
            const entity = {
              crc,
              cra,
              dm,
              pm,
              mm,
              pi,
              id: formFieldId,
            }
            const tools = customForm.handleTools(tableField.fromDataChecksetupDTO)
            const target = tools.filter(tool => tool.tag === tag)[0]
            if (target && (target.disabled || target.enable == 0)) {
              entity[alias] = 1
            } else {
              const checked = customForm.form[`$${variable}--${tag}`]
              if (checked) {
                entity[alias] = 2
              } else {
                entity[alias] = 1
              }
            }
            mTable.push(entity)
          } else if (tableField.type === '3') {
            const f = customForm.form[embeddedTableKey]
            const arr = embeddedTable[embeddedTableKey]
            const columns = embeddedTableRendering[embeddedTableKey]
            const tools = this.handleTools(columns)
            const target = tools.filter(tool => tool.tag === tag)[0]
            for (let i = 0; i < arr.length; i++) {
              const cols = []
              const { tableFieldList } = arr[i]
              let status
              if (target && (target.disabled || target.enable === 0)) {
                status = 1
              } else {
                const checked = f[`$${embeddedTableKey}--${i}--${tag}`]
                if (checked) {
                  status = 2
                } else {
                  status = 1
                }
              }
              tableFieldList.forEach(tableField => {
                const { formDataId, crc, cra, dm, pm, mm, pi } = tableField
                if (formDataId) {
                  const entity = {
                    crc,
                    cra,
                    dm,
                    pm,
                    mm,
                    pi,
                    id: formDataId,
                  }
                  entity[alias] = status
                  cols.push(entity)
                }
              })
              eTable.push(cols)
            }
          }
        })
        const data = {
          projectId: localStorage.getItem('sys-project-id'),
          subjectDataId: formDataId,
          roleId: localStorage.getItem('roleId'),
          roleCode: localStorage.getItem('projectRoleCode'),
          subjectId: id,
          detailsSignReqList: mTable,
          embeddedDetailsSignReqList: eTable,
          ...params,
        }
        this.updateSign({ data }).then(res => {
          const { code } = res
          if (code === 200) {
            this.$message.success('操作成功')
            this.$emit('upload')
            this.upgrade()
          }
        })
      }
    },
    // 冻结
    handleFreeze() {
      const params = {
        id: this.tableStatus.formDataId,
        statusType: '1',
        status: '2',
        roleId: localStorage.getItem('roleId')
      }
      this.updateTableStatus({ params })
        .then(res => {
          const { code } = res
          if (code === 200) {
            this.$message.success('操作成功！')
            this.upgrade()
          }
        })
        .catch(error => {
          this.$message.error(error)
        })
    },
    // 解冻
    unfreeze() {
      const params = {
        id: this.tableStatus.formDataId,
        statusType: '1',
        status: '1',
        roleId: localStorage.getItem('roleId')
      }
      this.updateTableStatus({ params })
        .then(res => {
          const { code } = res
          if (code === 200) {
            this.$message.success('操作成功！')
            this.upgrade()
          }
        })
        .catch(error => {
          this.$message.error(error)
        })
    },
  },
}
</script>

<style lang="scss" scoped>
@import './form.scss';
</style>
